/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package util;

import entity.AddressEntity;
import entity.BackorderEntity;
import entity.BillOfMaterialEntity;
import entity.BomRawMaterialWeightEntity;
import entity.CompletedGoodsEntity;
import entity.CompletedGoodsLocationEntity;
import entity.CreditTermEntity;
import entity.CustomerAccountEntity;
import entity.CustomerEntity;
import entity.DepartmentEntity;
import entity.MarketSalesReportEntity;
import entity.MasterProductionScheduleMonthlyEntity;
import entity.MasterProductionScheduleWeeklyEntity;
import entity.PackingOrderEntity;
import entity.PersonEntity;
import entity.PriceListEntity;
import entity.ProductPercentageQuantityEntity;
import entity.ProductQuantityPriceEntity;
import entity.PurchaseOrderEntity;
import entity.RawMaterialEntity;
import entity.RawMaterialPurchaseOrderEntity;
import entity.RawMaterialPurchaseOrderReportEntity;
import entity.RawMaterialQuotationEntity;
import entity.RawMaterialRequirementWeeklyEntity;
import entity.RawMaterialsLocationEntity;
import entity.RightEntity;
import entity.RightLinkEntity;
import entity.RoleEntity;
import entity.SaleOrderReportEntity;
import entity.SalesLeadEntity;
import entity.SalesOrderEntity;
import entity.SalesQuotationEntity;
import entity.ShippingOrderEntity;
import entity.ShippingRequestEntity;
import entity.SystemUserEntity;
import entity.VendorEntity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.enterprise.context.ApplicationScoped;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Root;
import org.apache.log4j.Logger;
import type.AddressType;
import type.BackorderStatus;
import type.CustomerType;
import type.MarketSalesType;
import type.Month;
import type.PackingOrderStatus;
import type.PaymentMethod;
import type.ProductionType;
import type.RawMaterialPurchaseOrderStatus;
import type.SalesForecastPeriodType;
import type.SalesOrderStatus;
import type.SalesOrderType;
import type.ShippingOrderStatus;
import type.UserTitle;
import type.VendorType;
import util.Fixtures.CompletedGoods;
import util.Fixtures.CreditTerm;
import util.Fixtures.Department;
import util.Fixtures.RawMaterial;
import util.Fixtures.RawMaterial.Supplier;
import util.Fixtures.Right;
import util.Fixtures.Role;

/**
 *
 * @author thanhle
 */
@Singleton
@Startup
@ApplicationScoped
public class DataInitializer {

    private Logger log = Logger.getLogger(getClass());
    private static StringReader salesLeads = new StringReader(
            "andy,huang,24hour Fitness,purchase manager\n"
            + "eddie,yap,Supersports,purchase manager\n"
            + "sun,wei,NTUC,sales representitive\n"
            + "lu,wei,ClubCali,purchase manager\n");
    private static StringReader customers = new StringReader(
            "nikolai,rochnick,24hour Fitness,purchase manager\n"
            + "paul,tsier,Supersports,purchase manager\n");
    private static StringReader completedGoodsLocations = new StringReader(
            "CG-A1,CG-A2,CG-A3,CG-A4,CG-A5,"
            + "CG-B1,CG-B2,CG-B3,CG-B4,CG-B5,"
            + "CG-C1,CG-C2,CG-C3,CG-C4,CG-C5\n");
    private static StringReader rawMaterialsLocations = new StringReader(
            "RM-A1,RM-A2,RM-A3,RM-A4,RM-A5,"
            + "RM-B1,RM-B2,RM-B3,RM-B4,RM-B5,"
            + "RM-C1,RM-C2,RM-C3,RM-C4,RM-C5\n");
    private static StringReader priceList = new StringReader(
            "Directsales,Wholesales,0,200,300,45,40,35,40,35,32,Classic Nutri Bar (Nuts),50\n"
            + "Directsales,Wholesales,0,200,300,50,45,40,45,40,35,Classic Nutri Bar (Fruits),50\n"
            + "Directsales,Wholesales,0,200,300,50,45,40,45,40,35,Premium Power Bar (Chocolate Nuts),45\n"
            + "Directsales,Wholesales,0,200,300,55,50,45,50,45,40,Premium Power Bar (Redcurrant Fruits),45\n");
//    private static StringReader salesReport = new StringReader( 
//            "199,8,2011,1\n"
//            +"200,9,2011,1\n"
//            +"333,9,2011,1\n"
//            +"298,9,2011,1\n"
//            +"150,10,2011,1\n"
//            );
    @PersistenceContext(unitName = "MacTeam-warPU")
    private EntityManager em;

    @PostConstruct
    public void initialize() throws IOException {
        log.info("Server starting...");
        inputRoles();
        inputDepartments();
        inputCreditTerms();

        inputEmployees(new BufferedReader(Fixtures.users));
        inputSalesLead(new BufferedReader(salesLeads));
        inputCustomers(new BufferedReader(customers));
        inputPriceListandSalesReport(new BufferedReader(priceList));
        inputSalesReport(2010);// for creation of 2011 sales forecast
        inputSalesReport(2012); // for testing of monthly adjustment of 2012 sales forecast
        inputSalesReport(2011);
        inputRawMaterials();
        inputSuppliers();
        inputVendorRawMaterial();
        inputCGLocation(new BufferedReader(completedGoodsLocations));
        inputRMLocation(new BufferedReader(rawMaterialsLocations));
        inputCompletedGoodsDetail();

        inputQuotations();
        inputBom();
        inputMPSWeekly(2011, Month.JUNE, 4);
//        inputMPSWeekly(2011, Month.NOVEMBER, 4);
//        inputMPSWeekly(2011, Month.DECEMBER, 4);
//        inputMPSWeekly(2011, Month.OCTOBER, 5);
        inputMRPWeekly(2011, Month.OCTOBER);//initiate last Week of the Mrp for that month which contains the ON Hand Quantity
        inputRawMaterialPurchaseOrderReports(2011, Month.NOVEMBER);
        inputMPSMonthly(2011, Month.DECEMBER, 100, SalesForecastPeriodType.SecondHalf);
        inputMPSMonthly(2011, Month.JUNE, 101, SalesForecastPeriodType.FirstHalf);
//        inputBackOrder(2011, Calendar.NOVEMBER, 12);
//        inputBackOrder(2011, Calendar.DECEMBER, 7);
//        inputBackOrder(2012, Calendar.JUNE, 16);
       // inputPOrder();
        inputMarketSalesReport();
    }

    private void inputRoles() throws IOException {
        for (Role r : Role.values()) {
            RoleEntity roleEntity = new RoleEntity();
            roleEntity.setRoleName(r.getName());
            Collection<RightEntity> roleRights = roleEntity.getRights();
            for (Right right : r.getRights()) {
                //RightEntity existing = findRight(right.getName());
                if (findRight(right.getName()) == null) {
                    RightEntity existing = new RightEntity();
                    existing.setRightName(right.getName());
                    existing.setFolder(right.getFolder());
                    roleRights.add(existing);

                    for (String rightLinkString : right.getLinks()) {
                        //RightLinkEntity existingLink = findLink(rightLinkString);
                        //if (findLink(rightLinkString) == null) {
                        RightLinkEntity rightLink = new RightLinkEntity();
                        rightLink.setRightLink(rightLinkString);
                        existing.getLinks().add(rightLink);
                    }



                } else {
                    findRight(right.getName()).setFolder(right.getFolder());
                    roleRights.add(findRight(right.getName()));

                    for (String rightLinkString : right.getLinks()) {
                        //RightLinkEntity existingLink = findLink(rightLinkString);
                        //if (findLink(rightLinkString) == null) {
                        RightLinkEntity rightLink = new RightLinkEntity();
                        rightLink.setRightLink(rightLinkString);
                        findRight(right.getName()).getLinks().add(rightLink);
                    }



                    for (String rightLinkString : right.getLinks()) {
                        //RightLinkEntity existingLink = findLink(rightLinkString);
                        //if (findLink(rightLinkString) == null) {
                        RightLinkEntity rightLink = new RightLinkEntity();
                        rightLink.setRightLink(rightLinkString);

                    }

                }
            }
            em.persist(roleEntity);
        }
    }

    public RightEntity findRight(String rightName) {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT r FROM rights r WHERE r.rightName = '" + rightName + "'");
            RightEntity result = (RightEntity) query.getSingleResult();

            return result;
        } catch (NoResultException e) {
            return null;
        }
    }

    public RightLinkEntity findLink(String linkName) {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT l FROM rightLinkEntity l WHERE l.rightLink = '" + linkName + "'");
            RightLinkEntity result = (RightLinkEntity) query.getSingleResult();

            return result;
        } catch (NoResultException e) {
            return null;
        }
    }

    public RoleEntity findRole(String roleName) {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT r FROM roles r WHERE r.roleName = '" + roleName + "'");
            RoleEntity result = (RoleEntity) query.getSingleResult();
            return result;
        } catch (NoResultException e) {
            return null;
        }
    }

    public Collection<RoleEntity> findAllRole() {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT r FROM roles r");
            Collection<RoleEntity> result = (Collection<RoleEntity>) query.getResultList();
            return result;
        } catch (NoResultException e) {
            return null;
        }
    }

    private void inputCGLocation(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] rs = line.split(",");
            for (int counter = 0; counter < rs.length; counter++) {
//                LocationEntity location = new LocationEntity();
                CompletedGoodsLocationEntity completedGoodsLocationEntity = new CompletedGoodsLocationEntity();
                completedGoodsLocationEntity.setCapacityCase(1000);
                completedGoodsLocationEntity.setUsageCase(0);
                completedGoodsLocationEntity.setAreaCode(rs[counter]);
                //location.setAreaCode(rs[counter]);
                em.persist(completedGoodsLocationEntity);
            }
        }
    }

    private void inputRMLocation(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] rs = line.split(",");
            for (int counter = 0; counter < rs.length; counter++) {
//                LocationEntity location = new LocationEntity();
                RawMaterialsLocationEntity rawMaterialsLocationEntity = new RawMaterialsLocationEntity();
                rawMaterialsLocationEntity.setCapacityKg(1000);
                rawMaterialsLocationEntity.setUsageKg(0);
                rawMaterialsLocationEntity.setAreaCode(rs[counter]);
                //location.setAreaCode(rs[counter]);
                em.persist(rawMaterialsLocationEntity);
            }
        }
    }

    private void inputEmployees(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] rs = line.split(",");
            SystemUserEntity member = new SystemUserEntity();

            member.setFirstName(rs[0]);
            member.setLastName(rs[0]);
            member.setName(rs[0]);
            member.setPassword(PasswordEncryptor.encryptPassword(rs[1]));
            member.setTitle(UserTitle.Mr);
            member.getContact().setContactNumber(rs[2]);
            member.getContact().setEmail(rs[3]);

            //addresses for admin
            if (member.getName().equals("admin")) {
                AddressEntity address1 = new AddressEntity("street1", "Singapore", "Singapore", "Singapore", "118430");
                address1.setContact(member.getContact());
                address1.setType(AddressType.HomeAddress);

                AddressEntity address2 = new AddressEntity("street2", "China", "Sichuan", "Chengdu", "99734");
                address2.setContact(member.getContact());
                address2.setType(AddressType.BillingAddress);

                member.getContact().getAddresses().add(address1);
                member.getContact().getAddresses().add(address2);
            }

            member.getContact().setPerson(member);
            em.persist(member);
            em.flush();
        }

        setUserDepartements();
        assigneUserRoleRights();
    }

    private void setUserDepartements() {
        DepartmentEntity marketing = getDepartmentByName(Department.Marketing.getName());
        DepartmentEntity sales = getDepartmentByName(Department.Sales.getName());
        DepartmentEntity tech = getDepartmentByName(Department.TechnicalSupport.getName());
        DepartmentEntity salesPlanning = getDepartmentByName(Department.SalesPlanning.getName());
        DepartmentEntity productionPlanning = getDepartmentByName(Department.ProductionPlanning.getName());
        DepartmentEntity accountReceivable = getDepartmentByName(Department.AccountsReceivable.getName());
        DepartmentEntity accountPayable = getDepartmentByName(Department.AccountsPayable.getName());
        DepartmentEntity warehouse = getDepartmentByName(Department.Warehouse.getName());

        DepartmentEntity purchasing = getDepartmentByName(Department.Purchasing.getName());

        SystemUserEntity than = (SystemUserEntity) getPersonByName("than");
        than.setDepartment(accountPayable);
        accountPayable.getEmployees().add(than);
        accountPayable.setManager(than);

        SystemUserEntity nga = (SystemUserEntity) getPersonByName("nga");
        nga.setDepartment(purchasing);
        purchasing.getEmployees().add(nga);
        purchasing.setManager(nga);

        SystemUserEntity dan = (SystemUserEntity) getPersonByName("dan");
        dan.setDepartment(marketing);
        marketing.getEmployees().add(dan);

        SystemUserEntity lee = (SystemUserEntity) getPersonByName("lee");
        lee.setDepartment(sales);
        sales.getEmployees().add(lee);

        SystemUserEntity thanh = (SystemUserEntity) getPersonByName("thanh");
        thanh.setDepartment(sales);
        sales.getEmployees().add(thanh);
        sales.setManager(lee);

        SystemUserEntity admin = (SystemUserEntity) getPersonByName("admin");
        admin.setDepartment(tech);
        tech.getEmployees().add(admin);

        SystemUserEntity jason = (SystemUserEntity) getPersonByName("jason");
        jason.setDepartment(salesPlanning);
        salesPlanning.getEmployees().add(jason);
        salesPlanning.setManager(jason);

        SystemUserEntity leticia = (SystemUserEntity) getPersonByName("leticia");
        leticia.setDepartment(warehouse);
        warehouse.getEmployees().add(leticia);
        warehouse.setManager(leticia);
        //salesPlanning.setManager(jason);

        SystemUserEntity ed = (SystemUserEntity) getPersonByName("ed");
        ed.setDepartment(productionPlanning);
        productionPlanning.getEmployees().add(ed);
        productionPlanning.setManager(ed);

        SystemUserEntity feist = (SystemUserEntity) getPersonByName("feist");
        feist.setDepartment(accountReceivable);
        accountReceivable.getEmployees().add(feist);
        accountReceivable.setManager(feist);
        SystemUserEntity god = (SystemUserEntity) getPersonByName("god");
        god.setDepartment(sales);
        sales.getEmployees().add(god);
        em.merge(dan);
        em.merge(lee);
        em.merge(thanh);
        em.merge(admin);
        em.merge(jason);
        em.merge(feist);
        em.merge(ed);

        em.merge(than);

        em.merge(leticia);
        em.merge(nga);
        em.merge(marketing);
        em.merge(sales);
        em.merge(purchasing);
        em.merge(tech);
        em.merge(salesPlanning);
        em.merge(accountReceivable);
        em.merge(productionPlanning);
        em.merge(accountPayable);
    }

    private void assigneUserRoleRights() {
        RoleEntity purchasingEmployee = findRole(Role.PurchasingEmployee.getName());
        RoleEntity employee = findRole(Role.Employee.getName());
        RoleEntity manager = findRole(Role.Manager.getName());
        RoleEntity accountExecutive = findRole(Role.CustomerExecutive.getName());
        RoleEntity salesManager = findRole(Role.SalesManager.getName());
        RoleEntity techSupport = findRole(Role.ITAdmin.getName());
        RoleEntity techSupportManager = findRole(Role.ITManager.getName());
        RoleEntity salesPlanningManager = findRole(Role.SalesPlanningManager.getName());

        RoleEntity accountsReceivableManager = findRole(Role.AccountsReceivableManager.getName());
        RoleEntity accountsReceivableEmployee = findRole(Role.AccountsReceivableEmployee.getName());
        RoleEntity productionManager = findRole(Role.ProductionManager.getName());

        RoleEntity accountsPayableEmployee = findRole(Role.AccountsPayableEmployee.getName());
        RoleEntity accountsPayableManager = findRole(Role.AccountsPayableManager.getName());
        RoleEntity warehouseEmployee = findRole(Role.WarehouseEmployee.getName());


        SystemUserEntity nga = (SystemUserEntity) getPersonByName("nga");
        nga.getRoles().add(manager);
        manager.getUsers().add(nga);
        nga.getRoles().add(purchasingEmployee);
        purchasingEmployee.getUsers().add(nga);
        nga.getRoles().add(employee);
        employee.getUsers().add(nga);

        SystemUserEntity dan = (SystemUserEntity) getPersonByName("dan");
        dan.getRoles().add(employee);
        employee.getUsers().add(dan);

        SystemUserEntity lee = (SystemUserEntity) getPersonByName("lee");
        lee.getRoles().add(employee);
        employee.getUsers().add(lee);
        lee.getRoles().add(manager);
        manager.getUsers().add(lee);
        lee.getRoles().add(accountExecutive);
        accountExecutive.getUsers().add(lee);
        lee.getRoles().add(salesManager);
        salesManager.getUsers().add(lee);

        SystemUserEntity leticia = (SystemUserEntity) getPersonByName("leticia");
        leticia.getRoles().add(employee);
        employee.getUsers().add(leticia);
        leticia.getRoles().add(warehouseEmployee);
        warehouseEmployee.getUsers().add(leticia);

        SystemUserEntity thanh = (SystemUserEntity) getPersonByName("thanh");
        thanh.getRoles().add(employee);
        employee.getUsers().add(thanh);
        thanh.getRoles().add(accountExecutive);
        accountExecutive.getUsers().add(thanh);

        SystemUserEntity than = (SystemUserEntity) getPersonByName("than");
        than.getRoles().add(accountsPayableEmployee);
        than.getRoles().add(accountsPayableManager);
        accountsPayableEmployee.getUsers().add(than);
        than.getRoles().add(manager);
        manager.getUsers().add(than);
        than.getRoles().add(employee);
        employee.getUsers().add(than);



        SystemUserEntity admin = (SystemUserEntity) getPersonByName("admin");
        admin.getRoles().add(employee);
        employee.getUsers().add(admin);
        admin.getRoles().add(techSupport);
        techSupport.getUsers().add(admin);
        admin.getRoles().add(techSupportManager);
        techSupportManager.getUsers().add(admin);
        admin.getRoles().add(manager);
        manager.getUsers().add(admin);

        SystemUserEntity jason = (SystemUserEntity) getPersonByName("jason");
        jason.getRoles().add(salesPlanningManager);
        salesPlanningManager.getUsers().add(jason);
        jason.getRoles().add(manager);
        manager.getUsers().add(jason);
        jason.getRoles().add(employee);
        employee.getUsers().add(jason);

        SystemUserEntity ed = (SystemUserEntity) getPersonByName("ed");
        ed.getRoles().add(productionManager);
        productionManager.getUsers().add(ed);
        ed.getRoles().add(manager);
        manager.getUsers().add(ed);
        ed.getRoles().add(employee);
        employee.getUsers().add(ed);

        SystemUserEntity feist = (SystemUserEntity) getPersonByName("feist");
        feist.getRoles().add(accountsReceivableEmployee);
        accountsReceivableEmployee.getUsers().add(feist);
        feist.getRoles().add(accountsReceivableManager);
        accountsReceivableManager.getUsers().add(feist);
        feist.getRoles().add(employee);
        employee.getUsers().add(feist);
        feist.getRoles().add(manager);
        manager.getUsers().add(feist);

        SystemUserEntity god = (SystemUserEntity) getPersonByName("god");
        Collection<RoleEntity> roles = findAllRole();
        for (RoleEntity r : roles) {
            god.getRoles().add(r);

            r.getUsers().add(god);
        }


        em.merge(god);
        em.merge(dan);
        em.merge(lee);
        em.merge(thanh);
        em.merge(admin);
        em.merge(jason);
        em.merge(feist);
        em.merge(ed);

        em.merge(leticia);

        em.merge(nga);

        em.merge(employee);
        em.merge(accountExecutive);
        em.merge(salesManager);
        em.merge(techSupport);
        em.merge(salesPlanningManager);
        em.merge(manager);
        em.merge(accountsReceivableEmployee);
        em.merge(accountsReceivableManager);
        em.merge(productionManager);
        em.merge(warehouseEmployee);
    }

    public PersonEntity getPersonByName(String userName) {
        PersonEntity res = null;
        try {
            CriteriaBuilder builder = em.getCriteriaBuilder();
            javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
            Root<PersonEntity> dataObjectRoot = cq.from(PersonEntity.class);
            cq.select(dataObjectRoot);
            cq.where(builder.and(builder.equal(dataObjectRoot.get("name"), userName), builder.equal(dataObjectRoot.get("archived"), false)));

            res = (PersonEntity) em.createQuery(cq).getSingleResult();
        } catch (NoResultException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return res;
    }

    private void inputDepartments() throws IOException {
        for (Department d : Department.values()) {
            DepartmentEntity member = new DepartmentEntity();
            member.setName(d.getName());
            em.persist(member);
        }
    }

    private Collection<DepartmentEntity> getAllDepartment() {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
        Root<DepartmentEntity> dataObjectRoot = cq.from(DepartmentEntity.class);
        cq.select(dataObjectRoot);

        return (Collection<DepartmentEntity>) em.createQuery(cq).getResultList();
    }

    private DepartmentEntity getDepartmentByName(String name) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        javax.persistence.criteria.CriteriaQuery cq = builder.createQuery();
        Root<DepartmentEntity> dataObjectRoot = cq.from(DepartmentEntity.class);
        cq.select(dataObjectRoot);
        cq.where(builder.equal(dataObjectRoot.get("name"), name));
        return (DepartmentEntity) em.createQuery(cq).getSingleResult();
    }

    private void inputSalesLead(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] rs = line.split(",");
            SalesLeadEntity salesLead = new SalesLeadEntity();
            salesLead.setFirstName(rs[0]);
            salesLead.setLastName(rs[1]);
            salesLead.setCompanyName(rs[2]);
            salesLead.setJobTitle(rs[3]);
            salesLead.setArchived(false);
            salesLead.setCustomerType(CustomerType.Wholesales);

            salesLead.setPassword(PasswordEncryptor.encryptPassword("123"));
            salesLead.setName(rs[0]);
            salesLead.getContact().setPerson(salesLead);
            //salesLead.setCreatedBy(new SystemUserEntity());

            //addresses for admin
            if (salesLead.getName().equals("lu")) {
                AddressEntity address1 = new AddressEntity("1A Kent Ridget Rd", "Singapore", "Singapore", "Singapore", "118430");
                address1.setContact(salesLead.getContact());
                address1.setType(AddressType.ShippingAddress);

                AddressEntity address2 = new AddressEntity("xi er huang #3", "China", "Sichuan", "Chengdu", "99734");
                address2.setContact(salesLead.getContact());
                address2.setType(AddressType.BillingAddress);

                AddressEntity address3 = new AddressEntity("you yi er lu", "China", "Shandong", "Jinan", "827482");
                address3.setContact(salesLead.getContact());
                address3.setType(AddressType.ShippingAddress);

                salesLead.getContact().getAddresses().add(address1);
                salesLead.getContact().getAddresses().add(address2);
                salesLead.getContact().getAddresses().add(address3);
            }

            em.persist(salesLead);
        }
    }

    private void inputCustomers(BufferedReader reader) throws IOException {
        String line;
        SystemUserEntity lee = (SystemUserEntity) getPersonByName("lee");

        while ((line = reader.readLine()) != null) {
            String[] rs = line.split(",");
            CustomerEntity customer = new CustomerEntity();
            customer.setFirstName(rs[0]);
            customer.setName(rs[0]);
            customer.setLastName(rs[1]);
            customer.setCompanyName(rs[2]);
            customer.setJobTitle(rs[3]);
            customer.setArchived(false);
            customer.getContact().setPerson(customer);
            customer.setCustomerExecutive(lee);
            customer.setCustomerType(CustomerType.Directsales);

            if (customer.getName().equals("paul")) {
                AddressEntity address1 = new AddressEntity("1A Kent Ridget Rd", "Singapore", "Singapore", "Singapore", "118430");
                address1.setContact(customer.getContact());
                address1.setType(AddressType.ShippingAddress);

                AddressEntity address2 = new AddressEntity("xi er huang #3", "China", "Sichuan", "Chengdu", "99734");
                address2.setContact(customer.getContact());
                address2.setType(AddressType.BillingAddress);

                AddressEntity address3 = new AddressEntity("you yi er lu", "China", "Shandong", "Jinan", "827482");
                address3.setContact(customer.getContact());
                address3.setType(AddressType.ShippingAddress);

                customer.getContact().getAddresses().add(address1);
                customer.getContact().getAddresses().add(address2);
                customer.getContact().getAddresses().add(address3);
                customer.getContact().setEmail("lu_wei@nus.edu.sg");

            }

            em.persist(customer);

            if (customer.getName().equals("paul")) {
                CustomerAccountEntity account = new CustomerAccountEntity();
                account.setCreditTerm(defaultCredit);
                account.setCreditBalance(CreditTerm.Default.creditLimit);
                account.setCashBalance(0);
                account.setCustomer(customer);

                customer.setCustomerAccount(account);
                em.merge(customer);
            }
        }
    }
    private CompletedGoodsEntity hackGoodsToBeRemoved;

    private void inputPriceListandSalesReport(BufferedReader reader) throws IOException {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] rs = line.split(",");

            PriceListEntity priceList = new PriceListEntity();
            PriceListEntity priceList1 = new PriceListEntity();
            PriceListEntity priceList2 = new PriceListEntity();
            PriceListEntity priceList3 = new PriceListEntity();
            PriceListEntity priceList4 = new PriceListEntity();
            PriceListEntity priceList5 = new PriceListEntity();

//            ProductEntity product = new ProductEntity();
            CompletedGoodsEntity product = new CompletedGoodsEntity();
            product.setProductName(rs[11]);
            product.setCasesOfHour(Long.parseLong(rs[12]));
            em.persist(product);
            hackGoodsToBeRemoved = product;

            CompletedGoods goods = Fixtures.getCompletedGoodsByName(product.getProductName());
            goods.setDbId(product.getId());

            priceList.setType(CustomerType.Directsales);
            priceList1.setType(CustomerType.Directsales);
            priceList2.setType(CustomerType.Directsales);
            priceList3.setType(CustomerType.Wholesales);
            priceList4.setType(CustomerType.Wholesales);
            priceList5.setType(CustomerType.Wholesales);
            priceList.setTieredQuantity(Long.valueOf(rs[2]));
            priceList1.setTieredQuantity(Long.valueOf(rs[3]));
            priceList2.setTieredQuantity(Long.valueOf(rs[4]));
            priceList3.setTieredQuantity(Long.valueOf(rs[2]));
            priceList4.setTieredQuantity(Long.valueOf(rs[3]));
            priceList5.setTieredQuantity(Long.valueOf(rs[4]));
            priceList.setPrice(Double.parseDouble(rs[5]));
            priceList1.setPrice(Double.parseDouble(rs[6]));
            priceList2.setPrice(Double.parseDouble(rs[7]));
            priceList3.setPrice(Double.parseDouble(rs[8]));
            priceList4.setPrice(Double.parseDouble(rs[9]));
            priceList5.setPrice(Double.parseDouble(rs[10]));
            priceList.setProduct(product);
            priceList1.setProduct(product);
            priceList2.setProduct(product);
            priceList3.setProduct(product);
            priceList4.setProduct(product);
            priceList5.setProduct(product);
            em.persist(priceList);
            em.persist(priceList1);
            em.persist(priceList2);
            em.persist(priceList3);
            em.persist(priceList4);
            em.persist(priceList5);

            //initial salesReport
            Random random = new Random();

            for (int i = 1; i <= 12; i++) {

                // generate 12 months sales order reports for 2011
                SaleOrderReportEntity salesReport = new SaleOrderReportEntity();
                salesReport.setQuantity(random.nextInt(200) + 100);
                salesReport.setType(SalesOrderType.normal);
                salesReport.setMonthOfSales(Month.fromMonthNum(i));
                salesReport.setYearOfSales(2011);
                salesReport.setProduct(product);
                em.persist(salesReport);

            }

            for (int e = 1; e <= 12; e += 5) {
                //generate promo sales order within 12 months
                SaleOrderReportEntity salesReport2 = new SaleOrderReportEntity();
                salesReport2.setQuantity(random.nextInt(30) + 40);
                salesReport2.setType(SalesOrderType.promo);
                salesReport2.setMonthOfSales(Month.fromMonthNum(e));
                salesReport2.setYearOfSales(2011);
                salesReport2.setProduct(product);
                em.persist(salesReport2);
            }
        }
    }

    public void inputSalesReport(int year) throws IOException {

        CompletedGoodsEntity productA = findCompletedGoodByName("Classic Nutri Bar (Nuts)");
        CompletedGoodsEntity productB = findCompletedGoodByName("Classic Nutri Bar (Fruits)");
        CompletedGoodsEntity productC = findCompletedGoodByName("Premium Power Bar (Chocolate Nuts)");
        CompletedGoodsEntity productD = findCompletedGoodByName("Premium Power Bar (Redcurrant Fruits)");



        Random random = new Random();
        ArrayList<CompletedGoodsEntity> goodsList = new ArrayList<CompletedGoodsEntity>();
        goodsList.add(productA);
        goodsList.add(productB);
        goodsList.add(productC);
        goodsList.add(productD);


        for (int k = 0; k <= 3; k++) {

            CompletedGoodsEntity product = goodsList.get(k);

            for (int i = 1; i <= 12; i++) {

                // generate 12 months sales order reports 
                SaleOrderReportEntity salesReport = new SaleOrderReportEntity();
                salesReport.setQuantity(random.nextInt(200) + 3000);
                salesReport.setType(SalesOrderType.normal);
                salesReport.setMonthOfSales(Month.fromMonthNum(i));
                salesReport.setYearOfSales(year);
                salesReport.setProduct(product);
                em.persist(salesReport);

            }

            for (int e = 1; e <= 12; e += 5) {
                //generate promo sales order within 12 months
                SaleOrderReportEntity salesReport2 = new SaleOrderReportEntity();
                salesReport2.setQuantity(random.nextInt(30) + 400);
                salesReport2.setType(SalesOrderType.promo);
                salesReport2.setMonthOfSales(Month.fromMonthNum(e));
                salesReport2.setYearOfSales(year);
                salesReport2.setProduct(product);
                em.persist(salesReport2);
            }

//              for(int i= 1; i<=4;i++){
//                  //generate 4 months sales order reports for 2011
//                  
//                SaleOrderReportEntity salesReport = new SaleOrderReportEntity();
//                salesReport.setQuantity(random.nextInt(200)+100);
//                salesReport.setType(SalesOrderType.normal);
//                salesReport.setMonthOfSales(Month.fromMonthNum(i));
//                salesReport.setYearOfSales(year);
//                salesReport.setProduct(product);
//                em.persist(salesReport);
//                
//                
//                  
//              }
//              
//              for(int g= 3; g<=4; g++){
//                  // generate promo sales order reports for 2011
//                SaleOrderReportEntity salesReport2 = new SaleOrderReportEntity();
//                salesReport2.setQuantity(random.nextInt(30)+50);
//                salesReport2.setType(SalesOrderType.promo);
//                salesReport2.setMonthOfSales(Month.fromMonthNum(g));
//                salesReport2.setYearOfSales(year);
//                salesReport2.setProduct(product);
//                em.persist(salesReport2); 
//              }
        }
    }
    private CreditTermEntity defaultCredit;

    private void inputCreditTerms() {
        defaultCredit = new CreditTermEntity(CreditTerm.Default.creditLimit,
                CreditTerm.Default.maxRepayTime, CreditTerm.Default.lateCharges,
                CreditTerm.Default.discountRepayTime, CreditTerm.Default.discount);
        em.persist(defaultCredit);
        CreditTerm.Default.setDbId(defaultCredit.getId());
    }

    private void inputRawMaterials() throws IOException {
        for (RawMaterial d : RawMaterial.values()) {
            RawMaterialEntity rm = new RawMaterialEntity();
            rm.setProductName(d.getProductName());
            rm.setLotSize(d.getLotSize());
            rm.setShelfLife(d.getShelfLife());
            rm.setLeadTime(d.getLeadTime());
            em.persist(rm);
        }
    }

    private void inputQuotations() {
        CustomerEntity paul = (CustomerEntity) getPersonByName("paul");
        SystemUserEntity lee = (SystemUserEntity) getPersonByName("lee");
        ArrayList<AddressEntity> addresses = paul.getContact().getShippingAddresses();

        //quotation
        SalesQuotationEntity quotation = new SalesQuotationEntity();
        quotation.setCustomer(paul);
        quotation.setSystemUser(lee);
        quotation.setIndicativeLeadTime(new Date());

        ProductQuantityPriceEntity pqp = new ProductQuantityPriceEntity();
        pqp.setProduct(hackGoodsToBeRemoved);
        pqp.setPrice(2100);
        pqp.setQuantity(21);
        pqp.setPricePerUnit(2100 / 210);
        pqp.setSalesQuotation(quotation);

        quotation.getPqp().add(pqp);
        quotation.setValidity(new Date());
        quotation.setValid(true);
        em.persist(quotation);

        //purchase order
        PurchaseOrderEntity po = new PurchaseOrderEntity();
        po.setCustomer(paul);
        po.setSalesQuotation(quotation);
        po.setBillingAddress(addresses.get(0));
        po.setPaymentMethod(PaymentMethod.BankDraft);
        po.getProductQuantityPrice().add(pqp);

        //shipping requests (will be cascaded with po)
        ShippingRequestEntity r1 = new ShippingRequestEntity();
        r1.setProduct(hackGoodsToBeRemoved);
        r1.setQuantity(15);
        r1.setAddress(addresses.get(0));
        r1.setPurchaseOrder(po);
        r1.setShippingDate(new Date());

        ShippingRequestEntity r2 = new ShippingRequestEntity();
        r2.setProduct(hackGoodsToBeRemoved);
        r2.setQuantity(6);
        r2.setAddress(addresses.get(1));
        r2.setPurchaseOrder(po);
        r2.setShippingDate(new Date());

        po.getShippingRequests().add(r1);
        po.getShippingRequests().add(r2);
        em.persist(po);
        pqp.setPurchaseOrder(po);
        em.merge(pqp);

        //sales order
        SalesOrderEntity so = new SalesOrderEntity();
        so.setCustomer(paul);
        so.setPurchaseOrder(po);
        so.setSystemUser(lee);
        so.setStatus(SalesOrderStatus.Pending);
        so.setPromotion(false);
        em.persist(so);
        po.setSalesOrder(so);
        em.merge(po);

        //generate shipping orders & packing orders
        Collection<ShippingRequestEntity> shippingRequests = po.getShippingRequests();
        HashMap<AddressEntity, Collection<ShippingRequestEntity>> addToRequests = new HashMap<AddressEntity, Collection<ShippingRequestEntity>>();
        for (ShippingRequestEntity request : shippingRequests) {
            Collection<ShippingRequestEntity> requests = addToRequests.get(request.getAddress());
            if (requests == null) {
                requests = new ArrayList<ShippingRequestEntity>();
            }
            requests.add(request);
            addToRequests.put(request.getAddress(), requests);
        }

        for (AddressEntity add : addToRequests.keySet()) {

            //create shipping order
            ShippingOrderEntity shippingOrder = new ShippingOrderEntity();
            shippingOrder.setAddress(add);
            shippingOrder.setStatus(ShippingOrderStatus.pending);

            //create packing order
            PackingOrderEntity packingOrder = new PackingOrderEntity();
            packingOrder.setProductToQuantity(addToRequests.get(add));
            packingOrder.setShippingOrder(shippingOrder);
            packingOrder.setStatus(PackingOrderStatus.pending);

            shippingOrder.setPackingOrder(packingOrder);
            shippingOrder.setSalesOrder(so);
            em.persist(shippingOrder);

            so.getShippingOrder().add(shippingOrder);

            //link shipping requests to packing order
            for (ShippingRequestEntity sr : addToRequests.get(add)) {
                sr.setPackingOrder(packingOrder);
                em.merge(sr);
            }
        }
        em.merge(so);
    }

    //thanh 's zone 
    private void inputSuppliers() throws IOException {
        for (Supplier d : Supplier.values()) {
            VendorEntity member = new VendorEntity();
            member.setCompanyName(d.getCompanyName());
            member.setPassword(PasswordEncryptor.encryptPassword(d.getPassword()));
            member.setName(d.getName());
            member.setFirstName("ngan");
            member.setVendorType(VendorType.confirmed);
            member.setStar(3);
            member.setBankAccount("DBS12023");

            AddressEntity address1 = new AddressEntity("street1", "VietNam", "VietNam", "VietNam", "118430");
            address1.setContact(member.getContact());
            address1.setType(AddressType.HomeAddress);

            AddressEntity address2 = new AddressEntity("street2", "VietNam", "VietNam", "VietNam", "99734");
            address2.setContact(member.getContact());
            address2.setType(AddressType.BillingAddress);

            member.getContact().getAddresses().add(address1);
            member.getContact().getAddresses().add(address2);
            member.getContact().setEmail("letanthanh273@gmail.com");
            member.getContact().setContactNumber("83555492");
            member.getContact().setPerson(member);
            em.persist(member);
        }
    }

    public RawMaterialEntity findRawMaterial(String rightName) {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT r FROM RawMaterial r WHERE r.productName = '" + rightName + "'");
            RawMaterialEntity result = (RawMaterialEntity) query.getSingleResult();

            return result;
        } catch (NoResultException e) {
            System.out.println("cant not find" + rightName);
            return null;
        }
    }

    public void inputVendorRawMaterial() throws IOException {

        //raw material
        RawMaterialEntity oats = (RawMaterialEntity) findRawMaterial("Oats");
        RawMaterialEntity nutmegs = (RawMaterialEntity) findRawMaterial("Nutmeg");
        RawMaterialEntity cloves = (RawMaterialEntity) findRawMaterial("Cloves");
        RawMaterialEntity wheatGerm = (RawMaterialEntity) findRawMaterial("Wheat Germ");
        RawMaterialEntity canolaOil = (RawMaterialEntity) findRawMaterial("Canola Oil");
        //
        //    Collection<RawMaterialEntity> rms1= new ArrayList<RawMaterialEntity>();
        VendorEntity ut = getVendorByCompanyName("UnionOfSovietSocialist");
        wheatGerm.getVendor().add(ut);
        nutmegs.getVendor().add(ut);
        canolaOil.getVendor().add(ut);
        oats.getVendor().add(ut);
        ut.getRms().add(canolaOil);
        ut.getRms().add(oats);
        ut.getRms().add(nutmegs);
        ut.getRms().add(wheatGerm);
        em.merge(ut);

        VendorEntity utc = getVendorByCompanyName("UnitedNationHeaven");
        wheatGerm.getVendor().add(utc);
        nutmegs.getVendor().add(utc);
        canolaOil.getVendor().add(utc);
        oats.getVendor().add(utc);
        utc.getRms().add(canolaOil);
        utc.getRms().add(oats);
        utc.getRms().add(nutmegs);
        utc.getRms().add(wheatGerm);

//       RawMaterialPurchaseOrderEntity r = new RawMaterialPurchaseOrderEntity();
//       RawMaterialQuotationEntity r1 = new RawMaterialQuotationEntity();
//      
//        
//        r1.setRawMaterial(oats);
//    
//   
//             
//      r.setRmq(r1);
//       r.setStatus(RawMaterialPurchaseOrderStatus.settled);
//       r.setQuantity(100);
//       r.setCost(10);
//       r.setDateConfirmed(new Date());
//       
//      utc.getRawMaterialPurchases().add(r);
//    
//      
//          
//  Calendar cal = Calendar.getInstance();
//            cal.set(2011, 10, 1);
//       RawMaterialPurchaseOrderEntity r2 = new RawMaterialPurchaseOrderEntity();
//       RawMaterialQuotationEntity r3 = new RawMaterialQuotationEntity();
//      
//        r3.setRawMaterial(nutmegs);
//
//              
//      r2.setRmq(r3);
//       r2.setStatus(RawMaterialPurchaseOrderStatus.settled);
//       r2.setQuantity(200);
//       r2.setCost(10);
//       r2.setDateConfirmed(cal.getTime());
//      utc.getRawMaterialPurchases().add(r2);
//        em.merge(utc);
//  
//      
//    
//        em.merge(r);
//
// em.merge(r2);
        em.merge(utc);
        ////////////////////////////////////////////cl

        VendorEntity cl = getVendorByCompanyName("UtcCorporationOfViet");
        wheatGerm.getVendor().add(cl);
        nutmegs.getVendor().add(cl);
        cloves.getVendor().add(cl);
        oats.getVendor().add(cl);
        cl.getRms().add(cloves);
        cl.getRms().add(oats);
        cl.getRms().add(nutmegs);
        cl.getRms().add(wheatGerm);
        em.merge(cl);
        //////////////////////////////////////quaker

        VendorEntity qk = getVendorByCompanyName("USupplyOfAnyProduct");

        wheatGerm.getVendor().add(qk);
        nutmegs.getVendor().add(qk);

        qk.getRms().add(nutmegs);
        qk.getRms().add(wheatGerm);
        em.merge(qk);

        //////////////////

     VendorEntity qk1 = getVendorByCompanyName("UnbeatableOrganization");

        wheatGerm.getVendor().add(qk1);
        nutmegs.getVendor().add(qk1);

        qk1.getRms().add(nutmegs);
        qk1.getRms().add(wheatGerm);
        em.merge(qk1);

    }

    private void inputPOrder() throws IOException {
        RawMaterialPurchaseOrderEntity r = new RawMaterialPurchaseOrderEntity();
        RawMaterialQuotationEntity r1 = new RawMaterialQuotationEntity();
        RawMaterialEntity oats = (RawMaterialEntity) findRawMaterial("Oats");
        RawMaterialEntity nutmegs = (RawMaterialEntity) findRawMaterial("Nutmeg");
        VendorEntity utc = getVendorByCompanyName("UnitedNationHeaven");
        r1.setRawMaterial(nutmegs);

        r1.setVendor(utc);

        r.setRmq(r1);
        r.setStatus(RawMaterialPurchaseOrderStatus.reviewed);

        r.setQuantity(100);
        r.setCost(10);
        r.setDateConfirmed(new Date());
        r.setNote("Initialized Order.For demo purpose.Cant delete");
        utc.getRawMaterialPurchases().add(r);


        Calendar cal = Calendar.getInstance();
        cal.set(2011, 9, 1);


        RawMaterialPurchaseOrderEntity r2 = new RawMaterialPurchaseOrderEntity();
        RawMaterialQuotationEntity r3 = new RawMaterialQuotationEntity();

        r3.setRawMaterial(oats);
        r3.setVendor(utc);

        r2.setRmq(r3);
        r2.setStatus(RawMaterialPurchaseOrderStatus.reviewed);
        r2.setQuantity(200);
        r2.setCost(10);
        r2.setNote("Initialized Order.For demo purpose.Cant delete!");


        r2.setDateConfirmed(cal.getTime());
        utc.getRawMaterialPurchases().add(r2);

//
//        RawMaterialPurchaseOrderEntity r4 = new RawMaterialPurchaseOrderEntity();
//        RawMaterialQuotationEntity r5 = new RawMaterialQuotationEntity();
//
//        r5.setRawMaterial(oats);
//        r5.setVendor(utc);
//
//        r4.setRmq(r5);
//        r4.setStatus(RawMaterialPurchaseOrderStatus.fulfilled);
//        HashMap settleShip = r4.getSettleShip();
//        Double d = 4.0;
//        settleShip.put(new Date(), d);
//        r4.setQuantity(200);
//        r4.setCost(10);
//
//
//        r4.setDateConfirmed(cal.getTime());
//        utc.getRawMaterialPurchases().add(r4);

        em.merge(utc);


    }

    private VendorEntity getVendorByCompanyName(String name) {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT r FROM Vendor r WHERE r.companyName = '" + name + "'");
            VendorEntity result = (VendorEntity) query.getSingleResult();

            return result;
        } catch (NoResultException e) {
            return null;
        }
    }

    private CompletedGoodsEntity findCompletedGoodByName(String string) {
        try {
            Query query = (Query) em.createQuery(
                    "SELECT c FROM CompletedGoods c WHERE c.productName = '" + string + "'");
            CompletedGoodsEntity result = (CompletedGoodsEntity) query.getSingleResult();

            return result;
        } catch (NoResultException e) {

            return null;
        }
    }

    public void inputBom() throws IOException {

        CompletedGoodsEntity productA = findCompletedGoodByName("Classic Nutri Bar (Nuts)");
        CompletedGoodsEntity productB = findCompletedGoodByName("Classic Nutri Bar (Fruits)");
        CompletedGoodsEntity productC = findCompletedGoodByName("Premium Power Bar (Chocolate Nuts)");
        CompletedGoodsEntity productD = findCompletedGoodByName("Premium Power Bar (Redcurrant Fruits)");

        BillOfMaterialEntity bomA = new BillOfMaterialEntity();
        BillOfMaterialEntity bomB = new BillOfMaterialEntity();
        BillOfMaterialEntity bomC = new BillOfMaterialEntity();
        BillOfMaterialEntity bomD = new BillOfMaterialEntity();

        ArrayList<BillOfMaterialEntity> listA = new ArrayList<BillOfMaterialEntity>();
        ArrayList<BillOfMaterialEntity> listB = new ArrayList<BillOfMaterialEntity>();
        listA.add(bomA);
        listA.add(bomB);

        listB.add(bomC);
        listB.add(bomD);


        for (BillOfMaterialEntity bill : listA) {
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Oats"), 0.5));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cinnamon"), 0.01));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Nutmeg"), 0.005));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cloves"), 0.0025));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Honey"), 0.025));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Canola Oil"), 0.015));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Vitamin/Mineral Powder"), 0.01));

        }

        bomA.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Carob Chips"), 0.1));
        bomA.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Hazenuts"), 0.075));
        bomA.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cashew Nuts"), 0.075));
        bomA.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Walnuts"), 0.075));
        bomA.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Almonds"), 0.05));
        bomA.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Macadamias"), 0.05));

        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Carob Chips"), 0.05));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Hazenuts"), 0.025));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Redcurrants"), 0.025));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Rasins"), 0.1));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Dates"), 0.075));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Apricots"), 0.05));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Kiwis"), 0.05));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Apples"), 0.05));
        bomB.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Peaches"), 0.05));

        for (BillOfMaterialEntity bill : listB) {
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Oats"), 0.6));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Wheat Germ"), 0.125));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cinnamon"), 0.02));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Nutmeg"), 0.0075));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cloves"), 0.005));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Honey"), 0.035));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Canola Oil"), 0.025));
            bill.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Vitamin/Mineral Powder"), 0.025));

        }

        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Carob Chips"), 0.125));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Protein Powder"), 0.125));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cocoa Powder"), 0.15));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Hazenuts"), 0.1));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cashew Nuts"), 0.1));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Walnuts"), 0.1));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Almonds"), 0.075));
        bomC.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Macadamias"), 0.075));

        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Carob Chips"), 0.075));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Protein Powder"), 0.125));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Cocoa Powder"), 0.025));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Hazenuts"), 0.035));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Redcurrants"), 0.15));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Rasins"), 0.075));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Dates"), 0.075));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Apricots"), 0.05));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Kiwis"), 0.075));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Apples"), 0.05));
        bomD.getRawMaterialBreakDowns().add(new BomRawMaterialWeightEntity(findRawMaterial("Peaches"), 0.075));

        em.persist(bomA);
        em.persist(bomB);
        em.persist(bomC);
        em.persist(bomD);

        productA.setBom(bomA);
        productB.setBom(bomB);
        productC.setBom(bomC);
        productD.setBom(bomD);

        productA.setWeightPerCase(12);//in kg
        productB.setWeightPerCase(12);
        productC.setWeightPerCase(13.32);
        productD.setWeightPerCase(13.32);

        em.merge(productA);
        em.merge(productB);
        em.merge(productC);

        em.merge(productD);
    }

    public void inputMPSWeekly(int year, Month month, int weekNum) throws IOException {
        int yearOfSales = year;
 //month = Month.fromMonthNum(month.getMonthNum()+1);
        ProductionType classic = ProductionType.Classic;
        ProductionType premium = ProductionType.Premium;
        Random random = new Random();

        CompletedGoodsEntity productA = findCompletedGoodByName("Classic Nutri Bar (Nuts)");
        CompletedGoodsEntity productB = findCompletedGoodByName("Classic Nutri Bar (Fruits)");
        CompletedGoodsEntity productC = findCompletedGoodByName("Premium Power Bar (Chocolate Nuts)");
        CompletedGoodsEntity productD = findCompletedGoodByName("Premium Power Bar (Redcurrant Fruits)");

        for (int i = 1; i <= weekNum; i++) {

            MasterProductionScheduleWeeklyEntity weekA = new MasterProductionScheduleWeeklyEntity();
            MasterProductionScheduleWeeklyEntity weekB = new MasterProductionScheduleWeeklyEntity();

            weekA.setYearOfProduction(yearOfSales);
            weekB.setYearOfProduction(yearOfSales);
            weekA.setMonthOfProduction(month);
            weekB.setMonthOfProduction(month);

            weekA.setWeekOfProduction(i);
            weekB.setWeekOfProduction(i);

            weekA.setProductionType(classic);
            weekB.setProductionType(premium);


            Collection<ProductPercentageQuantityEntity> ppq1 = new ArrayList<ProductPercentageQuantityEntity>();
            ProductPercentageQuantityEntity alpha = new ProductPercentageQuantityEntity();
            alpha.setProduct(productA);
            alpha.setQuantity(random.nextInt(400) + 3120);
            alpha.setMpsWeekly1(weekA);

            ProductPercentageQuantityEntity bravo = new ProductPercentageQuantityEntity();
            bravo.setProduct(productB);
            bravo.setQuantity(random.nextInt(400) + 3200);
            bravo.setMpsWeekly1(weekA);

            Collection<ProductPercentageQuantityEntity> ppq2 = new ArrayList<ProductPercentageQuantityEntity>();
            ProductPercentageQuantityEntity charlie = new ProductPercentageQuantityEntity();
            charlie.setProduct(productC);
            charlie.setQuantity(random.nextInt(400) + 3100);
            charlie.setMpsWeekly1(weekB);

            ProductPercentageQuantityEntity delta = new ProductPercentageQuantityEntity();
            delta.setProduct(productD);
            delta.setQuantity(random.nextInt(400) + 3200);
            delta.setMpsWeekly1(weekB);

            em.persist(alpha);
            em.persist(bravo);
            em.persist(charlie);
            em.persist(delta);
            ppq1.add(alpha);
            ppq1.add(bravo);

            ppq2.add(charlie);
            ppq2.add(delta);

            weekA.setBreakdownByProduct1(ppq1);
            weekB.setBreakdownByProduct1(ppq2);

            if (i == 5) {

                Collection<ProductPercentageQuantityEntity> ppq3 = new ArrayList<ProductPercentageQuantityEntity>();
                ProductPercentageQuantityEntity echo = new ProductPercentageQuantityEntity();
                echo.setProduct(productA);
                echo.setQuantity(random.nextInt(200) + 200);
                echo.setMpsWeekly2(weekA);

                ProductPercentageQuantityEntity foxtrot = new ProductPercentageQuantityEntity();
                foxtrot.setProduct(productB);
                foxtrot.setQuantity(random.nextInt(100) + 200);
                foxtrot.setMpsWeekly2(weekA);

                Collection<ProductPercentageQuantityEntity> ppq4 = new ArrayList<ProductPercentageQuantityEntity>();
                ProductPercentageQuantityEntity golf = new ProductPercentageQuantityEntity();
                golf.setProduct(productC);
                golf.setQuantity(random.nextInt(200) + 100);
                golf.setMpsWeekly2(weekB);

                ProductPercentageQuantityEntity hotel = new ProductPercentageQuantityEntity();
                hotel.setProduct(productD);
                hotel.setQuantity(random.nextInt(100) + 200);
                hotel.setMpsWeekly2(weekB);

                em.persist(echo);
                em.persist(foxtrot);
                em.persist(golf);
                em.persist(hotel);

                ppq3.add(echo);
                ppq3.add(foxtrot);

                ppq4.add(golf);
                ppq4.add(hotel);

                weekA.setBreakdownByProduct2(ppq3);
                weekB.setBreakdownByProduct2(ppq4);

            }



            em.persist(weekA);
            em.persist(weekB);

        }
    }

    private void inputMRPWeekly(int i, Month month) {
        int year = i;
        Month monthOfProduction = month;
        Random random = new Random();
        List<RawMaterialEntity> materialList = new ArrayList<RawMaterialEntity>();
        for (RawMaterial d : RawMaterial.values()) {
            RawMaterialEntity rm = findRawMaterial(d.getProductName());
            materialList.add(rm);
        }

        for (RawMaterialEntity r : materialList) {
            // initiate 5 weeks of mrp for each raw material for that month
            RawMaterialRequirementWeeklyEntity mrp1 = new RawMaterialRequirementWeeklyEntity();
            RawMaterialRequirementWeeklyEntity mrp2 = new RawMaterialRequirementWeeklyEntity();
            RawMaterialRequirementWeeklyEntity mrp3 = new RawMaterialRequirementWeeklyEntity();
            RawMaterialRequirementWeeklyEntity mrp4 = new RawMaterialRequirementWeeklyEntity();
            RawMaterialRequirementWeeklyEntity mrp5 = new RawMaterialRequirementWeeklyEntity();
            List<RawMaterialRequirementWeeklyEntity> mrpList = new ArrayList<RawMaterialRequirementWeeklyEntity>();
            mrpList.add(mrp1);
            mrpList.add(mrp2);
            mrpList.add(mrp3);
            mrpList.add(mrp4);
            mrpList.add(mrp5);
            mrp1.setWeekOfProduction(1);
            mrp2.setWeekOfProduction(2);
            mrp3.setWeekOfProduction(3);
            mrp4.setWeekOfProduction(4);
            mrp5.setWeekOfProduction(5);


            for (RawMaterialRequirementWeeklyEntity g : mrpList) {
                g.setYearOfProduction(year);
                g.setMonthOfProduction(monthOfProduction);
                g.setRawMaterial(r);
            }
            mrp5.setOnHandQuantity(random.nextInt(300) + 200);
            mrp5.setIsLastWeek(true);
            em.persist(mrp1);
            em.persist(mrp2);
            em.persist(mrp3);
            em.persist(mrp4);
            em.persist(mrp5);
        }

    }

    private void inputRawMaterialPurchaseOrderReports(int i, Month month) {
        int year = i;
        Month monthOfProduction = month;
        Random random = new Random();
        List<RawMaterialEntity> materialList = new ArrayList<RawMaterialEntity>();
//        HashMap map = new HashMap();
        ArrayList<RawMaterialEntity> list1 = new ArrayList<RawMaterialEntity>();
        ArrayList<Long> list2 = new ArrayList<Long>();
        for (RawMaterial d : RawMaterial.values()) {
            RawMaterialEntity rm = findRawMaterial(d.getProductName());
            materialList.add(rm);
            list1.add(rm);
            list2.add(d.getScheduleReciept());
        }

        for (RawMaterialEntity r : materialList) {

            for (int k = 1; k <= r.getLeadTime(); k++) {
                RawMaterialPurchaseOrderReportEntity report = new RawMaterialPurchaseOrderReportEntity();
                report.setExpectedYearOfReceipt(year);
                report.setExpectedMonthOfReceipt(monthOfProduction);
//                 System.out.println("report month "+report.getExpectedMonthOfRecepit());
                report.setExpectedWeekOfReceipt(k);
                report.setProduct(r);

                report.setQuantity(list2.get(list1.indexOf(r)));
                em.persist(report);
            }
        }
    }

    private void inputBackOrder(int year, int month, int day) {
        Calendar testDate = new GregorianCalendar(year, month, day);
        Date requiredDate = testDate.getTime();
        BackorderEntity backOrder = new BackorderEntity();
        backOrder.setRequiredLeadTime(requiredDate);
        Random random = new Random();
//        SalesOrderEntity salesOrder = new SalesOrderEntity();
//        salesOrder.setBackorder(backOrder);
        
        Collection<ProductQuantityPriceEntity> pqpList = new ArrayList<ProductQuantityPriceEntity>();
        ProductQuantityPriceEntity pqp1 = new ProductQuantityPriceEntity();
        ProductQuantityPriceEntity pqp2 = new ProductQuantityPriceEntity();
        ProductQuantityPriceEntity pqp3 = new ProductQuantityPriceEntity();
        ProductQuantityPriceEntity pqp4 = new ProductQuantityPriceEntity();

        CompletedGoodsEntity productA = findCompletedGoodByName("Classic Nutri Bar (Nuts)");
        CompletedGoodsEntity productB = findCompletedGoodByName("Classic Nutri Bar (Fruits)");
        CompletedGoodsEntity productC = findCompletedGoodByName("Premium Power Bar (Chocolate Nuts)");
        CompletedGoodsEntity productD = findCompletedGoodByName("Premium Power Bar (Redcurrant Fruits)");

        pqp1.setProduct(productA);
        pqp2.setProduct(productB);
        pqp3.setProduct(productC);
        pqp4.setProduct(productD);

        pqp1.setQuantity(200 + random.nextInt(1000));
        pqp2.setQuantity(500 + random.nextInt(300));
        pqp3.setQuantity(600 + random.nextInt(400));
        pqp4.setQuantity(500 + random.nextInt(200));

//        pqp1.setQuantity(10);
//        pqp2.setQuantity(20);
//        pqp3.setQuantity(20);
//        pqp4.setQuantity(10);
//        pqp1.setQuantity(2+random.nextInt(10));
//        pqp2.setQuantity(5+random.nextInt(3));
//        pqp3.setQuantity(6+random.nextInt(4));
//        pqp4.setQuantity(5+random.nextInt(2));

        pqpList.add(pqp1);
        pqpList.add(pqp2);
        pqpList.add(pqp3);
        pqpList.add(pqp4);

        pqp1.setBackorder(backOrder);
        pqp2.setBackorder(backOrder);
        pqp3.setBackorder(backOrder);
        pqp4.setBackorder(backOrder);

        backOrder.setProductQuantityPriceList(pqpList);
        backOrder.setStatus(BackorderStatus.PQPCheckPending);

        em.persist(backOrder);



    }

    private void inputMPSMonthly(int year, Month month, int safetyStock, SalesForecastPeriodType type) {
        MasterProductionScheduleMonthlyEntity mps = new MasterProductionScheduleMonthlyEntity();
        mps.setYearOfProduction(year);
        mps.setMonthOfProduction(month);
        mps.setSafetyStock(safetyStock);
        mps.setSalesForecast(null);
        mps.setType(type);
        em.persist(mps);
    }
    
    private void inputCompletedGoodsDetail() {
        CompletedGoodsEntity productA = findCompletedGoodByName("Classic Nutri Bar (Nuts)");
        CompletedGoodsEntity productB = findCompletedGoodByName("Classic Nutri Bar (Fruits)");
        CompletedGoodsEntity productC = findCompletedGoodByName("Premium Power Bar (Chocolate Nuts)");
        CompletedGoodsEntity productD = findCompletedGoodByName("Premium Power Bar (Redcurrant Fruits)");

        ArrayList<CompletedGoodsEntity> listA = new ArrayList<CompletedGoodsEntity>();
        ArrayList<CompletedGoodsEntity> listB = new ArrayList<CompletedGoodsEntity>();

        listA.add(productA);
        listA.add(productB);
        listB.add(productC);
        listB.add(productD);

        for (CompletedGoodsEntity c : listA) {
            c.setWeightPerBar(50);
            c.setShelfLife(12);
            c.setCapacityPerMin(200);
            c.setBarsPerBox(24);
            c.setBoxesPerCase(10);
            em.merge(c);

        }

        for (CompletedGoodsEntity d : listB) {
            d.setWeightPerBar(66.6);
            d.setShelfLife(12);
            d.setCapacityPerMin(150);
            d.setBarsPerBox(20);
            d.setBoxesPerCase(10);
            em.merge(d);

        }


    }

    private void inputMarketSalesReport() {

        MarketSalesReportEntity reportA = new MarketSalesReportEntity(MarketSalesType.Nuts, 38800, 2006);
        MarketSalesReportEntity reportB = new MarketSalesReportEntity(MarketSalesType.Nuts, 31200, 2007);
        MarketSalesReportEntity reportC = new MarketSalesReportEntity(MarketSalesType.Nuts, 32500, 2008);
        MarketSalesReportEntity reportD = new MarketSalesReportEntity(MarketSalesType.Nuts, 39200, 2009);
        MarketSalesReportEntity reportE = new MarketSalesReportEntity(MarketSalesType.Nuts, 43700, 2010);

        MarketSalesReportEntity reportF = new MarketSalesReportEntity(MarketSalesType.Fruits, 27000, 2006);
        MarketSalesReportEntity reportG = new MarketSalesReportEntity(MarketSalesType.Fruits, 29670, 2007);
        MarketSalesReportEntity reportH = new MarketSalesReportEntity(MarketSalesType.Fruits, 34567, 2008);
        MarketSalesReportEntity reportI = new MarketSalesReportEntity(MarketSalesType.Fruits, 35678, 2009);
        MarketSalesReportEntity reportJ = new MarketSalesReportEntity(MarketSalesType.Fruits, 37010, 2010);

        em.persist(reportA);
        em.persist(reportB);
        em.persist(reportC);
        em.persist(reportD);
        em.persist(reportE);
        em.persist(reportF);
        em.persist(reportG);
        em.persist(reportH);
        em.persist(reportI);
        em.persist(reportJ);
    }
}
